const connectionMap = {}; // 键：自己的UserId 值：与自己建立连接的用户数组

const socketOnConnection = function (io) {
  io.on("connection", (socket) => {
    console.log(socket.id);

    //接收消息
    socket.on("sendMessage", (data, callback) => {
      const { Info, ChatContent, CreateTime } = data;
      let {
        UserId: fromUserId,
        Nickname: fromNickname,
        AvatarUrl: fromAvatarUrl,
      } = Info.from; // 发送方
      let {
        UserId: toUserId,
        Nickname: toNickname,
        AvatarUrl: toAvatarUrl,
      } = Info.to; //接收方

      //如果这条消息的接收方是客服 需要把“客服端"的接收方设置为这条消息的“发送方”
      if (toUserId == "0") {
        io.emit("whoSend", { ...Info.from });
      }

      //当“发送方”向“接收方”发送消息以后，如果“接收方”的连接列表，没有“发送方”。把“发送方”添加进“接收方”的连接列表
      if (
        connectionMap[toUserId].findIndex(
          (item) => item.UserId == fromUserId
        ) == -1
      ) {
        connectionMap[toUserId].push({ ...Info.from });
        console.log(connectionMap);
      }

      // 向"接收方客户端"发送消息
      io.emit(`${Info.to.UserId}`, {
        ...data,
        CreateTime: new Date().getTime(),
      });

      callback({
        states: "ok",
      });
    });
  });
};

module.exports = { socketOnConnection, connectionMap };
